package com.jiuli_travel.user_service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiuli_travel.user_service.mapper.UserMapper;
import com.jiuli_travel.user_service.model.dto.user.UserEditRequest;
import com.jiuli_travel.user_service.model.dto.user.UserUpdateRequest;
import com.jiuli_travel.user_service.model.entity.User;
import com.jiuli_travel.user_service.model.vo.UserVO;
import com.jiuli_travel.user_service.service.IUserService;
import com.jiuli_travel.utils.RedisConstants;
import com.jiuli_travel.utils.Result;
import com.jiuli_travel.utils.UserHolder;
import jakarta.servlet.http.HttpServletRequest;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private RedissonClient redissonClient;

    //注册
    @Override
    public Result register(String userAccount, String password, String rePassword) {
        //非空判断
        if(userAccount.isBlank() || password.isBlank() || rePassword.isBlank()){
            return Result.fail("账号或者密码错误");
        }
        //判断两次密码的输入是否一致
        if(!password.equals(rePassword)){
            return Result.fail("两次密码不一致");
        }
        //添加用户
        User user = createUser(userAccount, password);
        boolean save = false;
        try {
            save = save(user);
        }catch (Exception e) {
            System.out.println(e);
        }
        if(!save){
            return Result.fail("该用户名已经存在， 注册失败");
        }
        return Result.ok("注册成功");
    }

    //登录
    @Override
    public Result login(String userAccount, String password) {
        //非空判断
        if(userAccount.isEmpty() || password.isEmpty()){
            return Result.fail("账号或者密码错误");
        }
        //查询该用户是否存在
        User user = lambdaQuery()
                .eq(User::getUserAccount, userAccount)
                .eq(User::getUserPassword, password).one();
        if(user == null){
            return Result.fail("账号或者密码错误");
        }
        /**
         * TODO 校验该用户是否已经登录了 redis中查   // 出现问题， 引用数据类型比较地址  用Objects.equals(user.getId(), loginUserId)
         */
        AtomicBoolean isLogin = new AtomicBoolean(false);
        Iterable<String> keysByPattern = redissonClient.getKeys().getKeysByPattern(RedisConstants.LOGIN_USER_KEY + "*");
        keysByPattern.forEach(key -> {
            RBucket<UserVO> userVORBucket = redissonClient.getBucket(key);
            Long loginUserId = userVORBucket.get().getId();
            if(Objects.equals(user.getId(), loginUserId)){
                isLogin.set(true);
            }
        });
        if(isLogin.get()){
            return Result.fail("该账号已经登录");
        }
        // 生成一个登录标识返回给前端
        String token = UUID.randomUUID().toString();
/*        //存储用户的基本信息到缓存中
        UserCache.savaUser(token, BeanUtil.copyProperties(user, UserVO.class));*/
        // 存储用户的信息到redis中
        RBucket<UserVO> rBucket = redissonClient.getBucket(RedisConstants.LOGIN_USER_KEY + token);
        rBucket.set(BeanUtil.copyProperties(user, UserVO.class));
        rBucket.expire(30, TimeUnit.MINUTES); // 设置过期时间（30分钟）

        return Result.ok(token);
    }

    //编辑用户的信息
    @Override
    public void editUser(UserEditRequest userEditRequest) {
        //获取当前用户的信息
        UserVO userVO = UserHolder.getUser();
        User user = BeanUtil.copyProperties(userEditRequest, User.class);
        user.setId(userVO.getId());
        //更新
        updateById(user);
    }

    //更新用户的信息
    @Override
    public void updateUser(UserUpdateRequest userUpdateRequest) {
        //获取当前用户的信息
        UserVO userVO = UserHolder.getUser();
        User user = BeanUtil.copyProperties(userUpdateRequest, User.class);
        user.setId(user.getId());
        //更新
        updateById(user);

    }

    //根据 user_id 获取用户的信息
    @Override
    public Result getUserByUserId(Long userId) {
        /**
         * 查询user表的基础信息
         */
        User user = getById(userId);
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        return Result.ok(userVO);
    }

    //退出登录
    @Override
    public void logout() {

    }

    /**
     *  创建用户
     */
    private User createUser(String userAccount, String userPassword){
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(userPassword);
        user.setUserName("user_"+ RandomUtil.randomString(10));
        return user;
    }
}




